package com.ynny.chapter09.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@RequestMapping("/files")
public class DownloadController {

    @Value("D:/upload/")
    String path;

    @GetMapping("/download")
    public ResponseEntity download(@RequestParam(name = "fileName")
                           String fileName){
        //从某个路径下 保存一个新文件
        File file = new File(path + fileName);
        if (!file.exists()){
            return ResponseEntity.notFound().build();
        }
        //新建一个资源文件
        Resource resource = new FileSystemResource(file);

        //还有请求头相关信息
        //告诉浏览器这是一个附件下载
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=" + resource.getFilename());

        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);

    }
}
